module btoolkit.network {

	export class Http {

		/**
		 * 跨域访问：服务器配置：在response里添加
		 * response.setHeader("Access-Control-Allow-Origin", "*"); 
		 */

		public static get(url: string, succeedCallback: Function, errorCallback: Function = null, isResponseJson: boolean = false): void {
			var request = new Laya.HttpRequest();
			request.once(Laya.Event.COMPLETE, this, (e: any) => {
				succeedCallback(JSON.stringify(e));
			});
			request.once(Laya.Event.ERROR, this, (e: any) => {
				console.error("IOError(" + url + "): " + JSON.stringify(e));
				if (errorCallback != null) {
					errorCallback();
				}
			});
			request.send(url, "", "get", isResponseJson ? "json" : "text");
		}

		public static post(url: string, params: { [key: string]: Object }, succeedCallback: Function, errorCallback: Function = null, isRequestJson: boolean = false, isResponseJson: boolean = false): void {
			var request = new Laya.HttpRequest();
			request.once(Laya.Event.COMPLETE, this, (e: any) => {
				succeedCallback(JSON.stringify(e));
			});
			request.once(Laya.Event.ERROR, this, (e: any) => {
				console.error("IOError(" + url + "): " + JSON.stringify(e));
				if (errorCallback != null) {
					errorCallback();
				}
			});
			var headers = [];
			if (isRequestJson) {
				headers = ["Content-Type", "application/json"];
			} else {
				headers = ["Content-Type", "application/x-www-form-urlencoded"];
			}
			var paramsStr = "";
			if (isRequestJson) {
				paramsStr = JSON.stringify(params);
			} else {
				for (var key in params) {
					if (paramsStr == '') {
						paramsStr += key + "=" + params[key];
					} else {
						paramsStr += "&" + key + "=" + params[key];
					}
				}
			}
			request.send(url, paramsStr, "post", isResponseJson ? "json" : "text", headers);
		}

		public static getParamFromUrl(key: string): string {
			var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return r[2];//这里不能用js里面的unescape方法
			}
			return null;
		}

	}
}